package top.shen33.yang.controller;

import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.tomcat.util.http.fileupload.FileUpload;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import top.shen33.yang.base.R;
import top.shen33.yang.base.YmlConfig;
import top.shen33.yang.model.vo.UploadFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/file")
public class FileController {


    ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();

    @Autowired
    private YmlConfig ymlConfig;


    private List<UploadFile> fileList = new ArrayList<>();


    @RequestMapping("/upload")
    public Object upload(HttpServletRequest request,MultipartFile file) throws Exception{


        if(file==null || file.isEmpty()){

            return R.err("上传的文件为空");
        }

        String suffix="";
        String originalFilename = file.getOriginalFilename();

        int indx = originalFilename.indexOf(".");
        if(indx>=0){
            suffix=originalFilename.substring(indx);
        }
//        String dir = request.getSession().getServletContext().getRealPath("/upload");

        String dir= ymlConfig.getFileUploadPath();
        String timeStap = DateTime.now().toString("yyyyMMdd_HHmmss");

        String serverFileName = timeStap + "_" + originalFilename;
        File serverFile=new File(dir, serverFileName);
        file.transferTo(serverFile);

        UploadFile uploadFile = new UploadFile();
        uploadFile.setFileName(originalFilename);
        uploadFile.setCtime(new Date());
        uploadFile.setUuid(serverFileName);
        fileList.add(uploadFile);

        String jsonStr = JSON.toJSONString(fileList);
        File dest =new File(ymlConfig.getCfgPath(),"file.json");
        FileUtils.writeStringToFile(dest,jsonStr);

        return R.ok(serverFileName);


    }

    @RequestMapping("/sqlFileList")
    public Object sqlFileList() throws Exception{


        String sqlPath = ymlConfig.getSqlPath();
        File dir=new File(sqlPath);

        String[] list = dir.list();
        List<String> collect = Arrays.asList(list).stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        return R.ok(collect);
    }


    @RequestMapping("/getSqlFile")
    public Object getSqlFile(String fname) throws IOException {

        String sqlPath = ymlConfig.getSqlPath();
        File file=new File(sqlPath,fname);
        String str = FileUtils.readFileToString(file);
        return R.ok("read file",str);
    }


    @RequestMapping("/addSql")
    public Object addSql(String fname,String author,String desc,String fileStr) {

        String sqlPath = ymlConfig.getSqlPath();
        File file=new File(sqlPath,fname);

        String tmp="/* author: {author} */ \n\n /* 说明：{desc} */ \n\n";
        if(StringUtils.isBlank(author)){

            author ="";
        }

        if(StringUtils.isBlank(desc)){

            desc ="";
        }

        String replaceStr = tmp.replace("{author}", author).replace("{desc}", desc);

        String text=replaceStr+fileStr;
        try {
            FileUtils.write(file,text, Charset.forName("UTF-8"));
            return R.ok("write file",text);
        } catch (IOException e) {

            e.printStackTrace();
            return R.err("write file failed");
        }


    }


    @RequestMapping("/upload1")
    public Object upload1(MultipartFile file) throws Exception{


        if(file==null || file.isEmpty()){

            return R.err("上传的文件为空");
        }

        String originalFilename = file.getOriginalFilename();

        String suffix = "";
        if(originalFilename.contains(".")){

            suffix = originalFilename.substring(originalFilename.indexOf("."));
        }

        String dir= ymlConfig.getFileUploadPath();
        String timeStap = DateTime.now().toString("yyyyMMdd_HHmmss");

        String serverFileName = "/"+timeStap + "_" + ThreadLocalRandom.current().nextInt(1000)+suffix;
        File serverFile=new File(dir, serverFileName);
        file.transferTo(serverFile);


        return R.ok(serverFileName);


    }
}
